package rensoft.android.view;

import static rensoft.java.lang.Lang.is;
import static rensoft.java.lang.Lang.set;

import rensoft.java.lang.Callback;
import rensoft.java.lang.Factory;

import rensoft.android.HasActivity;
import rensoft.android.HasActivityPresenter;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;

public class DialogPresenter extends HasActivityPresenter {

  private static final String STATE_TITLE = "dialog_title";
  private static final String STATE_VISIBLE = "dialog_svisible";
  private Dialog dialog;
  private Callback<Dialog> dialogCreateListener;
  private int viewId;
  private int titleId;
  private Factory<Dialog> dialogFactory;

  public DialogPresenter(HasActivity hasActivity, int viewId) {
    super(hasActivity);
    this.viewId = viewId;
  }

  public <T extends HasActivity & Factory<Dialog>> DialogPresenter(T parent) {
    super(parent);
    dialogFactory = parent;
  }

  public void dismissDialog() {
    dialog.dismiss();
  }

  public boolean isDialogVisible() {
    return is(dialog);
  }

  @Override
  public void onPause() {
    super.onPause();
    if (is(dialog)) dialog.dismiss();
  }

  @Override
  public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    if (is(dialog)) {
      state.putBoolean(getStateKey(STATE_VISIBLE), true);
      state.putInt(getStateKey(STATE_TITLE), titleId);
    }
  }

  public void setDialogCreateListener(Callback<Dialog> dialogCreateListener) {
    this.dialogCreateListener = dialogCreateListener;
  }

  public void setTitleId(int titleId) {
    this.titleId = titleId;
  }

  public void showDialog() {
    dialog = createDialog();
    if (is(dialogCreateListener)) dialogCreateListener.onCall(dialog);
    dialog.setOnDismissListener(new OnDismissListener() {
      public void onDismiss(DialogInterface dialog) {
        onDialogDismiss();
      }
    });
    dialog.show();
  }

  protected Dialog createDialog() {
    if (set(viewId)) {
      Dialog dialog = new Dialog(activity);
      dialog.setCancelable(true);
      dialog.setContentView(viewId);
      if (set(titleId)) dialog.setTitle(getString(titleId));
      return dialog;
    } else return dialogFactory.create();
  }

  @Override
  protected void onCreateRestore(Bundle state) {
    super.onCreateRestore(state);
    if (state.containsKey(getStateKey(STATE_VISIBLE))) {
      setTitleId(state.getInt(getStateKey(STATE_TITLE), 0));
      showDialog();
    }
  }

  private String getStateKey(String key) {
    return key + "_" + viewId;
  }

  private void onDialogDismiss() {
    dialog = null;
  }
}
